using System;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Collections.Generic;
using System.Linq;

namespace ShowDesktopOneMonitor
{
    public class KeyboardHookManager : IDisposable
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_KEYUP = 0x0101;
        private const int WM_SYSKEYDOWN = 0x0104;
        private const int WM_SYSKEYUP = 0x0105;

        private LowLevelKeyboardProc _proc;
        private IntPtr _hookID = IntPtr.Zero;
        private readonly List<Keys> _pressedKeys = new List<Keys>();
        private readonly Keys[] _targetSequence;
        private readonly KeyModifiers _targetModifiers;
        private DateTime _lastKeyPressTime = DateTime.MinValue;
        private const int SEQUENCE_TIMEOUT_MS = 1000; // 1秒超时

        public event EventHandler HotKeySequenceDetected;

        public KeyboardHookManager(Keys key, KeyModifiers modifiers)
        {
            _targetSequence = new[] { Keys.LWin, Keys.LShiftKey, key };
            _targetModifiers = modifiers;
            _proc = HookCallback;
        }

        public void Start()
        {
            _hookID = SetHook(_proc);
        }

        public void Stop()
        {
            if (_hookID != IntPtr.Zero)
            {
                UnhookWindowsHookEx(_hookID);
                _hookID = IntPtr.Zero;
            }
        }

        private IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (var curProcess = System.Diagnostics.Process.GetCurrentProcess())
            using (var curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {
            if (nCode >= 0)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                Keys key = (Keys)vkCode;

                if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
                {
                    HandleKeyDown(key);
                }
                else if (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
                {
                    HandleKeyUp(key);
                }
            }
            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }

        private void HandleKeyDown(Keys key)
        {
            var now = DateTime.Now;
            if ((now - _lastKeyPressTime).TotalMilliseconds > SEQUENCE_TIMEOUT_MS)
            {
                _pressedKeys.Clear();
            }
            _lastKeyPressTime = now;

            // 添加严格的按键验证
            if (key == Keys.LWin)
            {
                // 如果是Windows键，确保它是第一个按下的键
                if (_pressedKeys.Count > 0)
                {
                    _pressedKeys.Clear();
                }
            }
            else if (key == Keys.LShiftKey)
            {
                // 如果是左Shift键，确保Windows键已经被按下
                if (!_pressedKeys.Contains(Keys.LWin))
                {
                    _pressedKeys.Clear();
                    return;
                }
            }
            else if (key == Keys.D)
            {
                // 如果是D键，确保Windows键和左Shift键都已经被按下
                if (!_pressedKeys.Contains(Keys.LWin) || !_pressedKeys.Contains(Keys.LShiftKey))
                {
                    _pressedKeys.Clear();
                    return;
                }
            }

            if (!_pressedKeys.Contains(key))
            {
                _pressedKeys.Add(key);
                CheckSequence();
            }
        }

        private void HandleKeyUp(Keys key)
        {
            _pressedKeys.Remove(key);
        }

        private void CheckSequence()
        {
            if (_pressedKeys.Count != _targetSequence.Length)
                return;

            // 检查修饰键
            bool modifiersMatch = true;
            if ((_targetModifiers & KeyModifiers.Windows) != 0 && !_pressedKeys.Contains(Keys.LWin))
                modifiersMatch = false;
            if ((_targetModifiers & KeyModifiers.Shift) != 0 && !_pressedKeys.Contains(Keys.LShiftKey))
                modifiersMatch = false;
            if ((_targetModifiers & KeyModifiers.Control) != 0 && !_pressedKeys.Contains(Keys.LControlKey))
                modifiersMatch = false;
            if ((_targetModifiers & KeyModifiers.Alt) != 0 && !_pressedKeys.Contains(Keys.LMenu))
                modifiersMatch = false;

            if (!modifiersMatch)
                return;

            // 检查按键序列
            bool sequenceMatch = true;
            for (int i = 0; i < _targetSequence.Length; i++)
            {
                if (_pressedKeys[i] != _targetSequence[i])
                {
                    sequenceMatch = false;
                    break;
                }
            }

            if (sequenceMatch)
            {
                HotKeySequenceDetected?.Invoke(this, EventArgs.Empty);
                _pressedKeys.Clear();
            }
        }

        public void Dispose()
        {
            Stop();
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);
    }
} 